<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="java.util.LinkedList"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Book Details</title>
</head>
<body>
	<h4>Book Detail Page</h4>

	Book :<%=request.getParameter("book")%>
	<br />
	<br />
	<a href="bookList.jsp">Return</a>

	<%
		// 获得当前查看的Book名称
		String bookName = request.getParameter("book");

		//获取所有的Cookie, 将其放入到LinkedList中
		Cookie[] cookies = request.getCookies();
		LinkedList<Cookie> bookCookies = new LinkedList<Cookie>();
		// 如果查看的Book已经在Cookie中, 将删除掉旧的Cookie, 创建一个新的Cookie
		Cookie existingCookie = null;

		if (cookies != null && cookies.length > 0) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().startsWith("BKL")) {
					bookCookies.addLast(cookie);

					if (cookie.getValue().equals(bookName)) {
						existingCookie = cookie;
					}
				}
			}
		}

		// 删掉已经存在的同名的Cookie
		if (existingCookie != null) {
			boolean flag = bookCookies.remove(existingCookie);
			existingCookie.setMaxAge(0);
			response.addCookie(existingCookie);
			System.out.println("删掉同名的书" + flag);
		}

		// 将本次传入的Book加入Cookie
		Cookie cookie = new Cookie("BKL_" + bookName, bookName);
		response.addCookie(cookie);
		bookCookies.addLast(cookie);

		// 若cookie的记录数超过5条, 则删除掉较早的记录
		int cookieCount = bookCookies.size();
		if (cookieCount > 5) {
			for (int i = cookieCount; i > 5; i--) {
				Cookie oldCookie = bookCookies.removeFirst();
				oldCookie.setMaxAge(0);
				response.addCookie(oldCookie);
			}
		}
	%>
</body>
</html>